<template>
  <div class="app-container">

    <el-container>
      <el-header>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-input
                  v-model="kwInput"
                  placeholder="输入关键词进行筛选"
                  class="input-with-select"
                  clearable
                  @keyup.native.enter="handleSearch"
                >
                  <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                </el-input>
              </el-col>
              <el-col :span="12">
                <el-button
                  type="success"
                  title="添加新账户"
                  icon="el-icon-plus"
                  @click="handleAction('create', '添加配置')"
                >新增
                </el-button>
                <el-button
                  type="primary"
                  icon="el-icon-magic-stick"
                  style="background-color: #1EB7E6; border-color: #1EB7E6; color: white;"
                  @click="showFactoryAICreator"
                >AI 创建
                </el-button>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-header>
      <el-container>
        <el-main>
          <el-table
            v-loading.body="listLoading"
            :data="data"
            border
            fit
            highlight-current-row
            :default-sort="{prop: 'create_at', order: 'descending'}"
            style="width: 100%"
            @sort-change="handleSort"
          >
            <el-table-column align="left" label="ID" prop="id" sortable="custom" width="60" />
            <el-table-column align="left" label="任务名称" prop="name" />
            <el-table-column align="left" label="prompt框架" prop="prompt_topic_id" sortable="custom">
              <template slot-scope="scope">
                {{ scope.row.prompt_topic_id + ' ' + scope.row.prompt_topic_title }}
              </template>
            </el-table-column>
            <el-table-column align="left" label="话题列表" prop="topic_folder_id" sortable="custom">
              <template slot-scope="scope">
                {{ scope.row.topic_folder_id + ' ' + scope.row.topic_folder_title }}
              </template>
            </el-table-column>
            <el-table-column align="left" label="循环列表" prop="need_loop_content" sortable="custom">
              <template slot-scope="scope">
                <el-tag
                  v-if="scope.row.need_loop_content && scope.row.loop_content_groups && scope.row.loop_content_groups.length"
                  type="success"
                  style="cursor: pointer;"
                  @click="showLoopListContent(scope.row)"
                >
                  {{ scope.row.loop_content_groups.length }}个列表组 ({{ getTotalItems(scope.row.loop_content_groups) }}项)
                </el-tag>
                <span v-else>无</span>
              </template>
            </el-table-column>
            <el-table-column align="left" label="动态内容" prop="dynamic_content_groups" sortable="custom">
              <template slot-scope="scope">
                <div v-if="scope.row.dynamic_content_groups && scope.row.dynamic_content_groups.length">
                  <el-tag
                    v-for="(group, index) in scope.row.dynamic_content_groups"
                    :key="index"
                    type="warning"
                    style="cursor: pointer; margin-right: 5px; margin-bottom: 5px;"
                    @click="showDynamicContent(scope.row)"
                  >
                    {{ group.name }} ({{ group.items ? group.items.length : 0 }}项)
                  </el-tag>
                </div>
                <span v-else>无</span>
              </template>
            </el-table-column>
            <el-table-column align="left" label="TPS" prop="post_every_topic" title="每个帖子发的篇数" sortable="custom" width="80px" />
            <el-table-column align="left" label="周期" prop="post_period_day" title="发帖周期" sortable="custom" width="100px" />
            <el-table-column align="left" label="PPS" prop="post_number_in_period" title="周期内帖子数量" sortable="custom" width="80px" />
            <el-table-column align="left" label="所有员工" prop="all_staff" sortable="custom">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.all_staff" type="success">所有员工</el-tag>
                <el-tag v-else type="info">{{ scope.row.staff_tag }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column align="left" label="客户tag" prop="crmcustomer_tag" sortable="custom" />
            <el-table-column align="left" label="完成进度" prop="process_percent" sortable="custom">
              <template slot-scope="scope">
                <el-progress :percentage="scope.row.process_percent" />
              </template>
            </el-table-column>
            <el-table-column align="left" label="停止" prop="is_finished" sortable="custom">
              <template slot-scope="scope">
                <el-switch v-model="scope.row.is_finished" />
              </template>
            </el-table-column>
            <el-table-column align="left" label="提示" prop="note" />
            <el-table-column align="center" label="操作" width="200" fixed="right">
              <template slot-scope="scope">
                <el-button
                  v-show="!scope.row.edit"
                  size="mini"
                  icon="el-icon-edit"
                  type="warning"
                  plain
                  @click="handleAction('edit', scope.row)"
                >修改
                </el-button>
                <el-button
                  v-show="!scope.row.edit"
                  size="mini"
                  icon="el-icon-delete"
                  type="danger"
                  plain
                  @click="handleAction('delete', scope.row)"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            v-if="data.length"
            background
            class="mt-pagination"
            :current-page="page"
            :page-sizes="[10,20,50,100]"
            :page-size="pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </el-main>
      </el-container>
    </el-container>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="70%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-tabs v-model="activeName">
        <el-tab-pane label="步骤1 创建新prompt" name="ai_assist">
          <el-form label-position="top" style=" margin: 0 auto;">
            <!-- 使用卡片分隔不同的操作区域 -->
            <el-card class="box-card" shadow="hover" style="margin-bottom: 20px;">
              <div slot="header" class="clearfix">
                <span style="font-weight: bold; font-size: 16px;">获取Prompt</span>
                <el-tag type="info" size="small" style="margin-left: 10px;">请选择获取方式</el-tag>
              </div>

              <el-tabs v-model="promptSourceTab" type="card">
                <el-tab-pane label="搜索现有模板" name="search">
                  <el-form-item>
                    <el-input v-model="promptId" placeholder="输入prompt模板ID" clearable style="margin-bottom: 10px;">
                      <el-button slot="append" icon="el-icon-search" @click="handleSearchTempTopic(promptId, 'temp_prompt_topic')">搜索</el-button>
                    </el-input>
                    <div v-if="promptId" style="color: #67C23A; font-size: 13px; margin-top: 5px;">
                      <i class="el-icon-success" /> 当前使用的Prompt ID: {{ promptId }}
                    </div>
                  </el-form-item>
                </el-tab-pane>

                <el-tab-pane label="AI智能创建" name="ai">
                  <el-form-item>
                    <el-input
                      v-model="aiPromptInput"
                      type="textarea"
                      :rows="4"
                      placeholder="例如：我是做xxx行业的，我想做一个facebook日常出货贴文的prompt"
                      style="margin-bottom: 10px;"
                    />
                    <el-button type="primary" :loading="aiGenerating" style="width: 100%;" @click="handleGeneratePrompt">
                      <i class="el-icon-magic-stick" /> AI创建prompt
                    </el-button>
                  </el-form-item>
                </el-tab-pane>
              </el-tabs>
            </el-card>

            <el-card class="box-card" shadow="hover">
              <div slot="header" class="clearfix">
                <span style="font-weight: bold; font-size: 16px;">Prompt编辑与保存</span>
                <el-tag v-if="promptId" type="success" size="small" style="margin-left: 10px;">ID: {{ promptId }}</el-tag>
              </div>
              <el-alert
                v-if="promptId"
                title="Prompt已保存"
                type="success"
                :description="`当前Prompt ID: ${promptId}，内容工厂设置中会关联此ID`"
                :closable="false"
                show-icon
                style="margin-bottom: 15px;"
              />
              <el-form-item>
                <div style="margin-bottom: 10px; color: #606266; font-size: 14px;">
                  请优化以下Prompt跟自己行业结合，可以添加使命、价值、联系方式等，支持使用步骤2的动态内容使用shortcode插入到以下prompt中
                </div>
                <el-input
                  v-model="generatedPrompt"
                  type="textarea"
                  :rows="12"
                  placeholder="AI生成的prompt将在这里显示，您可以根据需要进行编辑"
                  style="margin-bottom: 15px;"
                />
                <div style="display: flex; justify-content: flex-end;">
                  <AITask
                    v-if="generatedPrompt.length > 10"
                    style="margin-right: 10px;"
                    :task-name="'common'"
                    show_name="内容工厂测试"
                    :params="{prompt: generatedPrompt}"
                    :show-icon="false"
                    button-type="primary"
                    button-text="测试效果"
                    dialog-title="Prompt测试结果"
                  />
                  <el-button type="success" :disabled="!generatedPrompt" size="mini" @click="applyGeneratedPrompt">
                    <i class="el-icon-check" /> {{ promptId ? '更新Prompt' : '保存Prompt' }}
                  </el-button>
                </div>
              </el-form-item>
            </el-card>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="步骤2 动态内容" name="dynamic_content">
          <el-form label-position="left" label-width="120px" style=" width: 100%;">
            <div style="border: 1px solid #e6e6e6; padding: 15px; margin-bottom: 20px; border-radius: 4px;">
              <h3 style="margin-top: 0; display: flex; justify-content: space-between; align-items: center;">
                <span>动态内容列表</span>
                <div>
                  <el-button
                    type="info"
                    icon="el-icon-refresh"
                    size="small"
                    :loading="loadingStates[dynamicStrategyName]"
                    style="margin-right: 10px;"
                    @click="fetchContentData(dynamicStrategyName)"
                  >
                    刷新列表
                  </el-button>
                  <el-button type="primary" icon="el-icon-plus" size="small" @click="addDynamicContentGroup">新增动态内容组</el-button>
                </div>
              </h3>

              <el-alert
                title="动态内容说明"
                type="info"
                description="可以创建多组动态内容，每组包含一个名称和多个素材项。创建任务时会随机选择一个素材。"
                :closable="false"
                show-icon
                style="margin-bottom: 15px;"
              />

              <div v-if="contentDataCache[dynamicStrategyName] && contentDataCache[dynamicStrategyName].length > 0" style="margin-bottom: 20px;">
                <el-alert
                  title="Shortcode格式"
                  type="success"
                  :description="`可以在prompt中插入动态内容，使用 {{topic_ID_description_random_1}} 格式的shortcode，ID为动态内容组的ID`"
                  :closable="false"
                  show-icon
                  style="margin-bottom: 15px;"
                />
                <h4>已创建的动态内容：</h4>
                <el-table
                  v-loading="loadingStates[dynamicStrategyName]"
                  :data="contentDataCache[dynamicStrategyName]"
                  style="width: 100%"
                  row-key="id"
                  border
                >
                  <el-table-column
                    prop="id"
                    label="ID"
                    width="160"
                  />
                  <el-table-column
                    prop="keyword"
                    label="名称"
                    width="200"
                  />
                  <el-table-column
                    label="素材数量"
                    width="120"
                  >
                    <template slot-scope="scope">
                      <span>{{ scope.row.children_count }}个素材</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="预览"
                    width="120"
                  >
                    <template slot-scope="scope">
                      <el-button
                        type="text"
                        size="small"
                        @click="previewDynamicContent(scope.row)"
                      >
                        查看素材
                      </el-button>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="操作"
                    width="200"
                  >
                    <template slot-scope="scope">
                      <el-button
                        type="text"
                        size="small"
                        @click="copyShortcode(scope.row.id)"
                      >
                        复制shortcode
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>

                <div style="margin-top: 10px; text-align: left; font-size: 12px; color: #999;">
                  <p>动态内容列表状态: {{ loadingStates[dynamicStrategyName] ? '加载中' : '已加载' }}</p>
                  <p>动态内容数量: {{ contentDataCache[dynamicStrategyName] ? contentDataCache[dynamicStrategyName].length : 0 }}</p>
                  <p v-if="loadingStates[dynamicStrategyName]">正在从服务器获取数据...</p>
                </div>
              </div>

              <div v-if="temp.dynamic_content_groups && temp.dynamic_content_groups.length > 0">
                <div
                  v-for="(group, groupIndex) in temp.dynamic_content_groups"
                  :key="'group-'+groupIndex"
                  style="border: 1px solid #ebeef5; border-radius: 4px; margin-bottom: 20px; padding: 15px; position: relative;"
                >

                  <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                    <div style="font-weight: bold; font-size: 16px;">新增动态内容组 #{{ groupIndex + 1 }}</div>
                    <el-button
                      type="danger"
                      icon="el-icon-delete"
                      size="mini"
                      @click="removeDynamicContentGroup(groupIndex)"
                    />
                  </div>

                  <el-form-item label="动态内容名称" label-width="120px">
                    <div style="display: flex; align-items: center;">
                      <el-input v-model="group.name" placeholder="例如：价值体系列表，7大体系列表内容" style="flex: 1;" />
                      <el-button
                        type="primary"
                        size="small"
                        :disabled="!group.name.trim()"
                        style="margin-left: 10px;"
                        :loading="group.savingName"
                        @click="saveContentGroupName(groupIndex, dynamicStrategyName)"
                      >
                        保存名称
                      </el-button>
                    </div>
                    <div v-if="group.id" style="margin-top: 5px; color: #67C23A;">
                      <i class="el-icon-check" /> ID: {{ group.id }}
                    </div>
                  </el-form-item>

                  <el-form-item label="动态内容素材" label-width="120px">
                    <div
                      v-for="(item, itemIndex) in group.items"
                      :key="'item-'+groupIndex+'-'+itemIndex"
                      style="display: flex; margin-bottom: 15px;"
                    >
                      <el-input
                        v-model="group.items[itemIndex]"
                        type="textarea"
                        :rows="3"
                        style="flex: 1;"
                        placeholder="输入素材内容，支持多行文本"
                      />
                      <div style="display: flex; flex-direction: column; margin-left: 10px;">
                        <el-button
                          type="success"
                          icon="el-icon-check"
                          size="mini"
                          :disabled="!group.id || !group.items[itemIndex].trim()"
                          :loading="group.savingItems && group.savingItems[itemIndex]"
                          style="margin-bottom: 5px;"
                          @click="saveContentItem(groupIndex, itemIndex, dynamicStrategyName)"
                        >
                          保存
                        </el-button>
                        <el-button
                          type="danger"
                          icon="el-icon-delete"
                          size="mini"
                          @click="removeDynamicContentItem(groupIndex, itemIndex)"
                        />
                      </div>
                    </div>
                    <el-button
                      type="primary"
                      icon="el-icon-plus"
                      size="small"
                      :disabled="!group.id"
                      style="margin-top: 10px;"
                      @click="addDynamicContentItem(groupIndex)"
                    >
                      新增素材
                    </el-button>
                    <div v-if="!group.id" style="margin-top: 10px; color: #E6A23C;">
                      <i class="el-icon-warning" /> 请先保存动态内容名称
                    </div>
                  </el-form-item>
                </div>
              </div>

              <div v-else>
                <el-button type="primary" @click="addDynamicContentGroup">新增动态内容组</el-button>
              </div>

              <div style="margin-top: 15px; text-align: right;">
                <el-button type="success" :loading="savingPreviewChanges" @click="savePreviewChanges()">
                  批量保存
                </el-button>
              </div>
            </div>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="步骤3 循环列表" name="loop_list">
          <el-form label-position="left" label-width="120px" style="width: 100%;">
            <el-form-item label="是否需要循环创建不同主题内容？" label-width="240px">
              <el-switch v-model="temp.need_loop_content" />
            </el-form-item>

            <div v-if="temp.need_loop_content" style="border: 1px solid #e6e6e6; padding: 15px; margin-bottom: 20px; border-radius: 4px;">
              <h3 style="margin-top: 0; display: flex; justify-content: space-between; align-items: center;">
                <span>循环列表配置</span>
                <div>
                  <el-button
                    type="info"
                    icon="el-icon-refresh"
                    size="small"
                    :loading="loadingStates[loopStrategyName]"
                    style="margin-right: 10px;"
                    @click="fetchContentData(loopStrategyName)"
                  >
                    刷新列表
                  </el-button>
                  <el-button type="primary" icon="el-icon-plus" size="small" @click="addLoopContentGroup">新增循环列表组</el-button>
                </div>
              </h3>

              <el-alert
                title="循环列表说明"
                type="info"
                description="可以创建多组循环列表，每组包含一个名称和多个列表项。创建任务时会遍历每个列表项创建不同内容。"
                :closable="false"
                show-icon
                style="margin-bottom: 15px;"
              />

              <div v-if="contentDataCache[loopStrategyName] && contentDataCache[loopStrategyName].length > 0" style="margin-bottom: 20px;">
                <h4>已创建的循环列表：</h4>
                <el-table
                  v-loading="loadingStates[loopStrategyName]"
                  :data="contentDataCache[loopStrategyName]"
                  style="width: 100%"
                  row-key="id"
                  border
                >
                  <el-table-column
                    prop="id"
                    label="ID"
                    width="160"
                  />
                  <el-table-column
                    prop="keyword"
                    label="列表名称"
                    width="200"
                  />
                  <el-table-column
                    label="列表项数量"
                    width="120"
                  >
                    <template slot-scope="scope">
                      <span>{{ scope.row.children_count }}个列表项</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="预览"
                    width="120"
                  >
                    <template slot-scope="scope">
                      <el-button
                        type="text"
                        size="small"
                        @click="previewLoopContent(scope.row)"
                      >
                        查看列表项
                      </el-button>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="操作"
                    width="200"
                  >
                    <template slot-scope="scope">
                      <el-button
                        :type="(scope.row.id !== undefined && temp.topic_folder_id !== undefined && scope.row.id.toString() === temp.topic_folder_id.toString()) ? 'primary' : 'text'"
                        size="small"
                        @click="useLoopContent(scope.row.id)"
                      >
                        {{ (scope.row.id !== undefined && temp.topic_folder_id !== undefined && scope.row.id.toString() === temp.topic_folder_id.toString()) ? '✓ 当前已选择' : '使用列表项' }}
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>

                <div style="margin-top: 10px; text-align: left; font-size: 12px; color: #999;">
                  <p>循环列表状态: {{ loadingStates[loopStrategyName] ? '加载中' : '已加载' }}</p>
                  <p>循环列表数量: {{ contentDataCache[loopStrategyName] ? contentDataCache[loopStrategyName].length : 0 }}</p>
                  <p v-if="loadingStates[loopStrategyName]">正在从服务器获取数据...</p>
                </div>
              </div>

              <div v-if="temp.loop_content_groups && temp.loop_content_groups.length > 0">
                <div
                  v-for="(group, groupIndex) in temp.loop_content_groups"
                  :key="'group-'+groupIndex"
                  style="border: 1px solid #ebeef5; border-radius: 4px; margin-bottom: 20px; padding: 15px; position: relative;"
                >

                  <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                    <div style="font-weight: bold; font-size: 16px;">新增循环列表组 #{{ groupIndex + 1 }}</div>
                    <el-button
                      type="danger"
                      icon="el-icon-delete"
                      size="mini"
                      @click="removeLoopContentGroup(groupIndex)"
                    />
                  </div>

                  <el-form-item label="循环列表名称" label-width="120px">
                    <div style="display: flex; align-items: center;">
                      <el-input v-model="group.name" placeholder="例如：产品列表，关键词列表" style="flex: 1;" />
                      <el-button
                        type="primary"
                        size="small"
                        :disabled="!group.name.trim()"
                        style="margin-left: 10px;"
                        :loading="group.savingName"
                        @click="saveContentGroupName(groupIndex, loopStrategyName)"
                      >
                        保存名称
                      </el-button>
                    </div>
                    <div v-if="group.id" style="margin-top: 5px; color: #67C23A;">
                      <i class="el-icon-check" /> ID: {{ group.id }}
                    </div>
                  </el-form-item>

                  <el-form-item label="循环列表项目" label-width="120px">
                    <div
                      v-for="(item, itemIndex) in group.items"
                      :key="'item-'+groupIndex+'-'+itemIndex"
                      style="display: flex; margin-bottom: 15px;"
                    >
                      <el-input
                        v-model="group.items[itemIndex]"
                        type="textarea"
                        :rows="3"
                        style="flex: 1;"
                        placeholder="输入列表项内容，支持多行文本"
                      />
                      <div style="display: flex; flex-direction: column; margin-left: 10px;">
                        <el-button
                          type="success"
                          icon="el-icon-check"
                          size="mini"
                          :disabled="!group.id || !group.items[itemIndex].trim()"
                          :loading="group.savingItems && group.savingItems[itemIndex]"
                          style="margin-bottom: 5px;"
                          @click="saveContentItem(groupIndex, itemIndex, loopStrategyName)"
                        >
                          保存
                        </el-button>
                        <el-button
                          type="danger"
                          icon="el-icon-delete"
                          size="mini"
                          @click="removeLoopContentItem(groupIndex, itemIndex)"
                        />
                      </div>
                    </div>
                    <el-button
                      type="primary"
                      icon="el-icon-plus"
                      size="small"
                      :disabled="!group.id"
                      style="margin-top: 10px;"
                      @click="addLoopContentItem(groupIndex)"
                    >
                      新增列表项
                    </el-button>
                    <div v-if="!group.id" style="margin-top: 10px; color: #E6A23C;">
                      <i class="el-icon-warning" /> 请先保存循环列表名称
                    </div>
                  </el-form-item>
                </div>
              </div>

              <div v-else>
                <el-button type="primary" @click="addLoopContentGroup">新增循环列表组</el-button>
              </div>

              <div style="margin-top: 15px; text-align: right;">
                <el-button type="success" :loading="savingLoopListChanges" @click="saveLoopListChanges()">
                  批量保存
                </el-button>
              </div>
            </div>

            <div v-else>
              <el-alert
                title="未启用循环列表功能"
                type="info"
                description="启用循环列表功能后，可以配置产品列表、关键词列表等循环创建不同主题内容"
                :closable="false"
                show-icon
              />
            </div>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="步骤4 内容工厂设置" name="first" style="max-width: 600px">
          <el-form ref="dataForm" :model="temp" label-position="left" label-width="120px">
            <el-form-item label="任务名称" label-width="120px">
              <el-input v-model="temp.name" />
            </el-form-item>
            <el-form-item label="prompt模板ID" label-width="120px">
              <el-input v-model="temp.prompt_topic_id" placeholder="输入prompt模板ID" @change="handleSearchTopic(temp.prompt_topic_id, 'temp_prompt_topic')">
                <el-button slot="append" icon="el-icon-search" @click="handleSearchTopic(temp.prompt_topic_id, 'temp_prompt_topic')" />
              </el-input>

              <el-popover
                v-if="temp_prompt_topic"
                placement="top-start"
                title="prompt模板"
                width="800"
                trigger="click"
              >
                <el-descriptions v-if="temp_prompt_topic" title="话题信息" :column="1">
                  <el-descriptions-item label="title">{{ temp_prompt_topic.title }}</el-descriptions-item>
                  <el-descriptions-item label="keyword">{{ temp_prompt_topic.keyword }}</el-descriptions-item>
                  <el-descriptions-item label="description">
                    <el-input v-model="temp_prompt_topic.description" type="textarea" rows="3" disabled />
                  </el-descriptions-item>
                </el-descriptions>
                <el-tag v-if="temp_prompt_topic" slot="reference">{{ temp_prompt_topic.title }}</el-tag>
              </el-popover>
            </el-form-item>
            <el-form-item label="话题列表ID" label-width="120px">
              <el-input v-model="temp.topic_folder_id" placeholder="输入话题列表目录ID" @change="handleSearchTopic(temp.topic_folder_id, 'temp_topic_folder')">
                <el-button slot="append" icon="el-icon-search" @click="handleSearchTopic(temp.topic_folder_id, 'temp_topic_folder')" />
              </el-input>
              <el-popover
                v-if="temp_topic_folder"
                placement="top-start"
                title="话题列表"
                width="800"
                trigger="click"
              >
                <el-descriptions v-if="temp_topic_folder" title="话题列表" :column="1">
                  <el-descriptions-item label="title">{{ temp_topic_folder.title }}</el-descriptions-item>
                  <el-descriptions-item label="keyword">{{ temp_topic_folder.keyword }}</el-descriptions-item>
                  <el-descriptions-item label="description">
                    <el-input v-model="temp_topic_folder.description" type="textarea" rows="3" disabled />
                  </el-descriptions-item>
                </el-descriptions>
                <el-tag v-if="temp_topic_folder" slot="reference">{{ temp_topic_folder.title }}</el-tag>
              </el-popover>
            </el-form-item>
            <el-form-item label="每个话题发帖数量" label-width="120px">
              <el-input-number v-model="temp.post_every_topic" :min="-1" style="width: 100%;" />
              <el-tag>-1表示没有限制</el-tag>
            </el-form-item>
            <el-form-item label="帖子周期（天）" label-width="120px">
              <el-input-number v-model="temp.post_period_day" :min="1" style="width: 100%;" />
            </el-form-item>
            <el-form-item label="周期内发帖量" label-width="120px">
              <el-input-number v-model="temp.post_number_in_period" :min="1" style="width: 100%;" />
            </el-form-item>
            <el-form-item label="客户tag" label-width="120px">
              <el-input v-model="temp.crmcustomer_tag" clearable @blur="handleSearchCRMCustomer">
                <el-button slot="append" :loading="crmcustomer_loading" title="搜索关联客户数量" icon="el-icon-search" @click="handleSearchCRMCustomer" />
              </el-input>
              <el-alert v-if="crmcustomer_total === 0" :closable="false" title="用于批量客户邮件,默认不用填" type="error" />
              <el-alert v-else :closable="false" :title="'关联客户数量' + crmcustomer_total" type="success" />
            </el-form-item>
            <el-form-item v-if="temp.crmcustomer_tag === ''" label="所有员工" label-width="120px">
              <el-switch v-model="temp.all_staff" />
            </el-form-item>
            <el-form-item v-if="!temp.all_staff" label="关联员工分组" label-width="120px">
              <el-tag
                v-for="tag in temp.staff_tag"
                :key="tag"
                closable
                :disable-transitions="false"
                @close="handleClose(tag)"
              >
                {{ tag }}
              </el-tag>
              <el-autocomplete
                v-if="inputVisible"
                ref="saveTagInput"
                v-model="inputValue"
                class="input-new-tag"
                :fetch-suggestions="querySearch"
                placeholder="输入标签,回车确认"
                size="small"
                style="width: 200px;"
                @select="handleAddTag"
                @keyup.enter.native="handleInputConfirm"
              />
              <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 新标签</el-button>
            </el-form-item>

            <el-form-item label="停止" label-width="120px">
              <el-switch v-model="temp.is_finished" />
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <!-- <el-tab-pane label="步骤5 邮件营销" name="second">
            <div v-if="temp.id">
                <cmsautomailtask :task_id="temp.id"></cmsautomailtask>
            </div>
            <div v-else>
              请先保存之后，再创建邮件营销任务
            </div>
          </el-tab-pane> -->
      </el-tabs>

      <span slot="footer" class="dialog-footer">
        <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 循环列表内容查看对话框 -->
    <el-dialog
      title="循环列表内容详情"
      :visible.sync="loopListDialogVisible"
      width="70%"
    >
      <div v-if="currentLoopList" v-loading="loadingLoopListItems">
        <h3 style="display: flex; justify-content: space-between; align-items: center;">
          <span>{{ currentLoopList.name }}</span>
          <div>
            <el-pagination
              v-if="currentLoopList.total > 0"
              background
              :current-page="loopItemPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="loopItemPageSize"
              layout="total, sizes, prev, pager, next"
              :total="currentLoopList.total"
              style="display: inline-block; margin-right: 15px;"
              @size-change="handleLoopItemSizeChange"
              @current-change="handleLoopItemPageChange"
            />
            <el-button type="primary" size="small" @click="addLoopListItem">新增列表项</el-button>
          </div>
        </h3>
        <el-table :data="currentLoopList.content" border>
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column prop="value" label="内容">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.value"
                type="textarea"
                :rows="3"
                placeholder="列表项内容"
                style="width: 100%;"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <el-button
                type="success"
                icon="el-icon-check"
                size="small"
                :loading="scope.row.saving"
                @click="saveLoopListItem(scope.$index)"
              >
                ·
              </el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="small"
                @click="removeLoopListItem(scope.$index)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 15px; text-align: right;">
          <el-button type="success" :loading="savingLoopListChanges" @click="saveLoopListChanges()">
            批量保存
          </el-button>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="loopListDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>

    <!-- 动态内容查看对话框 -->
    <el-dialog
      :title="dialogContentTitle"
      :visible.sync="dynamicContentDialogVisible"
      width="90%"
    >
      <div v-loading="loadingStates.materialPreview" element-loading-text="正在加载内容...">
        <div v-if="materialContentList && materialContentList.length">
          <div
            v-for="(group, groupIndex) in materialContentList"
            :key="'dialog-group-'+groupIndex"
            style="margin-bottom: 20px; border-bottom: 1px solid #EBEEF5; padding-bottom: 15px;"
          >
            <h3 style="display: flex; justify-content: space-between; align-items: center;">
              <span>{{ group.keyword || '未命名组' }}</span>
              <div>
                <el-pagination
                  v-if="dynamicContentTotal > 0"
                  background
                  :current-page="dynamicContentPage"
                  :page-sizes="[10, 20, 50, 100]"
                  :page-size="dynamicContentPageSize"
                  layout="total, sizes, prev, pager, next"
                  :total="dynamicContentTotal"
                  style="display: inline-block; margin-right: 15px;"
                  @size-change="handleDynamicContentSizeChange"
                  @current-change="handleDynamicContentPageChange"
                />
                <el-button type="primary" size="small" @click="addItemToPreview(group)">新增内容项</el-button>
              </div>
            </h3>
            <el-empty v-if="!group.children || group.children.length === 0" description="暂无内容" />
            <el-table v-else :data="group.children" border>
              <el-table-column type="index" label="序号" width="80" />
              <el-table-column prop="description" label="内容">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.description"
                    type="textarea"
                    :rows="3"
                    placeholder="内容"
                    style="width: 100%;"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200">
                <template slot-scope="scope">
                  <el-button
                    type="success"
                    icon="el-icon-check"
                    size="small"
                    :loading="scope.row.saving"
                    @click="saveDynamicContentItem(group, scope.$index)"
                  >
                    保存
                  </el-button>
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    size="small"
                    @click="removeItemFromPreview(group, scope.$index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div style="margin-top: 15px; text-align: right;">
            <el-button type="success" :loading="savingPreviewChanges" @click="savePreviewChanges()">
              批量保存
            </el-button>
          </div>
        </div>
        <el-empty v-else description="暂无数据" />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dynamicContentDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>

    <!-- AI 创建内容工厂对话框 -->
    <FactoryAICreator
      :visible.sync="factoryAICreatorVisible"
      @created="handleFactoryCreated"
    />
  </div>
</template>

<script>
import { Get, Post, Put, Delete, PostRandomContent, GetRandomContent } from '@/api/cms/autopostgeneratetask'
import { Get as GetCrmCustomer } from '@/api/crm/crmcustomer'
import { Get as GetTopic } from '@/api/cms/topic'
import { CRMGetProjectUsers } from '@/api/crm/crmmanage'
import qs from 'qs'
import Cmsautomailtask from './elements/cmsautomailtask'
// 导入OpenAI API以及文件系统模块来读取prompt模板
import { Post as GetAiContent } from '@/api/cms/openai'
// 引入AITask组件
import AITask from '@/components/AITask'
// 引入FactoryAICreator组件
import FactoryAICreator from '@/components/FactoryAICreator'

// 定义常量
const DYNAMIC_STRATEGY_NAME = '内容工厂-动态素材'
const LOOP_STRATEGY_NAME = '内容工厂-循环列表' // 如果需要全局获取循环列表的顶级目录，可以使用此常量

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}

export default {
  name: 'Autopostgeneratetask',
  components: { Cmsautomailtask, AITask, FactoryAICreator },
  data() {
    return {
      activeName: 'ai_assist',
      title: '新增配置',
      listLoading: false,
      dialogVisible: false,
      loopListDialogVisible: false,
      dynamicContentDialogVisible: false,
      savingRandomContent: false,
      currentLoopList: null,
      currentDynamicContent: null,
      temp_prompt_topic: null,
      temp_topic_folder: null,
      tags: [],
      staffs: [],
      inputVisible: false,
      inputValue: '',
      temp: {
        name: '',
        staff_tag: [],
        prompt_topic_id: null,
        topic_folder_id: '',
        post_every_topic: 3,
        post_period_day: 7,
        crmcustomer_tag: '',
        post_number_in_period: 2,
        all_staff: true,
        is_finished: false,
        process_percent: 0,
        need_loop_content: false,
        loop_content_groups: [],
        dynamic_content_groups: []
      },
      crmcustomer_total: 0,
      crmcustomers: [],
      crmcustomer_loading: false,
      topics: [],
      kwInput: '',
      action: '',
      data: [],
      order_by: '',
      order_desc: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,
      aiPromptInput: '',
      aiGenerating: false,
      generatedPrompt: '',
      contentFactoryPromptTemplate: '',
      // --- Unified Content Data ---
      contentDataCache: {}, // Stores fetched content lists { strategyName: [...] }
      loadingStates: {}, // Stores loading states { strategyName: boolean, materialPreview: boolean }
      materialContentList: [], // For dynamic content preview dialog (children)
      // --- End Unified Content Data ---
      savingPreviewChanges: false,
      savingLoopContent: false,
      currentPreviewItemId: null,
      currentPreviewStrategyName: null,
      // --- Strategy Names ---
      dynamicStrategyName: DYNAMIC_STRATEGY_NAME,
      loopStrategyName: LOOP_STRATEGY_NAME,
      loadingLoopListItems: false,
      loopItemPage: 1,
      loopItemPageSize: 20,
      dynamicContentPage: 1,
      dynamicContentPageSize: 20,
      dynamicContentTotal: 0,
      savingLoopListChanges: false,
      promptDialogVisible: false,
      savingPrompt: false,
      promptForm: {
        description: '',
        keyword: ''
      },
      promptId: null,
      promptChanged: false,
      isEditing: false,
      promptSourceTab: 'search',
      // AI 创建相关
      factoryAICreatorVisible: false
    }
  },
  computed: {
    dialogContentTitle() {
      if (!this.currentPreviewStrategyName) return '内容列表'
      return this.currentPreviewStrategyName === this.dynamicStrategyName
        ? '动态内容素材列表' : '循环列表项目'
    }
  },
  created() {
    this.getList()
    this.handleGetStaffs()
    this.fetchContentData(this.dynamicStrategyName)
    this.fetchContentData(this.loopStrategyName)

    // 初始化content factory prompt模板
    this.contentFactoryPromptTemplate = `你是一个prompt内通创建专家。
请根据用户的要求
<用户要求>{{user_content}}</用户要求>
创建一个结构完整的prompt`
  },
  methods: {
    // AI 创建相关方法
    showFactoryAICreator() {
      this.factoryAICreatorVisible = true
    },
    handleFactoryCreated(taskId) {
      this.$message.success('内容工厂创建成功！')
      this.factoryAICreatorVisible = false
      // 刷新列表
      this.getList()
    },
    useLoopContent(id) {
      // 确保id不为undefined或null
      if (id === undefined || id === null) return

      // 如果当前已选择该ID，则取消选择
      if (this.temp.topic_folder_id !== undefined && this.temp.topic_folder_id !== null &&
          id.toString() === this.temp.topic_folder_id.toString()) {
        this.temp.topic_folder_id = ''
        this.$message({
          message: '已取消选择循环列表',
          type: 'info'
        })
      } else {
        // 否则选择该ID
        this.temp.topic_folder_id = id
        this.$message({
          message: '已选择循环列表',
          type: 'success'
        })
      }
    },
    handleSearchCRMCustomer() {
      if (this.temp.crmcustomer_tag === '') {
        this.crmcustomer_total = 0
        this.crmcustomers = []
        this.crmcustomer_loading = false
        return
      }
      this.crmcustomer_loading = true
      GetCrmCustomer(null, qs.stringify({
        kw: this.temp.crmcustomer_tag,
        pagesize: 10,
        page: 1
      })).then(response => {
        this.crmcustomer_total = response.data.total
        this.$message({
          message: '关联客户数量' + response.data.total,
          type: 'success'
        })
        this.crmcustomer_loading = false
      })
    },
    handleGetStaffs() {
      CRMGetProjectUsers(null, qs.stringify({
        pagesize: 1000,
        page: 1
      }))
        .then(response => {
          this.staffs = response.data.data
          this.tags = response.data.tags
        }).catch(err => {
          console.log(err)
        })
    },
    querySearch(queryString, cb) {
      // 直接生成value数组表
      const results = this.tags.map(tag => ({ value: tag }))
      cb(results)
    },
    handleAddTag(item) {
      console.log(item)
      if (!this.temp.staff_tag.includes(item.value)) {
        this.temp.staff_tag.push(item.value)
        this.inputValue = ''
      }
    },
    handleClose(tag) {
      this.temp.staff_tag.splice(this.temp.staff_tag.indexOf(tag), 1)
    },

    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.temp.staff_tag.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    handleSearchTempTopic(promptid) {
      GetTopic(null, qs.stringify({
        kw: promptid,
        pagesize: 10,
        page: 1
      })).then(response => {
        if (response.data && response.data.data) {
          this.generatedPrompt = response.data.data[0].description
          this.aiPromptInput = response.data.data[0].keyword
        }
      })
    },
    handleSearchTopic(query, temp) {
      GetTopic(null, qs.stringify({
        kw: query,
        pagesize: 10,
        page: 1
      })).then(response => {
        if (temp === 'temp_prompt_topic') this.temp_prompt_topic = response.data.data[0]
        if (temp === 'temp_topic_folder') this.temp_topic_folder = response.data.data[0]
      })
    },
    resetTemp() {
      this.temp = {
        name: '',
        staff_tag: [],
        prompt_topic_id: null,
        topic_folder_id: '',
        post_every_topic: 3,
        post_period_day: 7,
        crmcustomer_tag: '',
        post_number_in_period: 2,
        all_staff: true,
        is_finished: false,
        process_percent: 0,
        need_loop_content: false,
        loop_content_groups: [],
        dynamic_content_groups: []
      }
      this.temp_prompt_topic = null
      this.temp_topic_folder = null
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.dialogVisible = true
          this.title = '添加'
          this.resetTemp()
          break
        case 'edit':
          this.title = '编辑任务:' + row.name
          Object.keys(this.temp).forEach(key => {
            if (row[key] !== undefined) this.temp[key] = row[key]
          })
          this.temp.id = row.id
          this.handleSearchTopic(this.temp.prompt_topic_id, 'temp_prompt_topic')
          this.handleSearchTopic(this.temp.topic_folder_id, 'temp_topic_folder')
          this.dialogVisible = true
          break
        case 'delete':
          this.dialogVisible = true
          this.title = `确认要删除${row.name}?`
          this.temp = row
          break
      }
    },
    changeWPAccount(v) {
      this.temp.wpaccount_id = v
    },
    confirm() {
      const _data = this.temp

      // 处理循环列表数据
      if (_data.need_loop_content) {
        // 验证循环列表数据
        if (!_data.loop_content_groups || !_data.loop_content_groups.length) {
          this.$notify({
            title: '错误',
            message: '请添加循环列表内容',
            type: 'error',
            duration: 2000
          })
          return
        }

        // 验证每个循环列表组
        for (let i = 0; i < _data.loop_content_groups.length; i++) {
          const group = _data.loop_content_groups[i]

          // 检查名称
          if (!group.name || !group.name.trim()) {
            this.$notify({
              title: '错误',
              message: `第${i + 1}个循环列表组名称不能为空`,
              type: 'error',
              duration: 2000
            })
            return
          }

          // 检查是否有列表项
          if (!group.items || !group.items.length) {
            this.$notify({
              title: '错误',
              message: `第${i + 1}个循环列表组"${group.name}"至少需要一项列表项`,
              type: 'error',
              duration: 2000
            })
            return
          }

          // 过滤空的列表项
          group.items = group.items.filter(item => item && item.trim && item.trim() !== '')

          if (!group.items.length) {
            this.$notify({
              title: '错误',
              message: `第${i + 1}个循环列表组"${group.name}"的列表项不能为空`,
              type: 'error',
              duration: 2000
            })
            return
          }
        }
      }

      // 处理动态内容数据
      if (_data.dynamic_content_groups && _data.dynamic_content_groups.length > 0) {
        // 验证每个动态内容组
        for (let i = 0; i < _data.dynamic_content_groups.length; i++) {
          const group = _data.dynamic_content_groups[i]

          // 检查名称
          if (!group.name || !group.name.trim()) {
            this.$notify({
              title: '错误',
              message: `第${i + 1}个动态内容组名称不能为空`,
              type: 'error',
              duration: 2000
            })
            return
          }

          // 检查是否有素材
          if (!group.items || !group.items.length) {
            this.$notify({
              title: '错误',
              message: `第${i + 1}个动态内容组"${group.name}"至少需要一项素材`,
              type: 'error',
              duration: 2000
            })
            return
          }

          // 过滤空的素材项
          group.items = group.items.filter(item => item && item.trim && item.trim() !== '')

          if (!group.items.length) {
            this.$notify({
              title: '错误',
              message: `第${i + 1}个动态内容组"${group.name}"的素材内容不能为空`,
              type: 'error',
              duration: 2000
            })
            return
          }
        }
      }

      switch (this.action) {
        case 'create':
          // 如果没有name，或者其他参数不能提交
          if (!_data.name) {
            this.$notify({
              title: '错误',
              message: '请填写任务名称',
              type: 'error',
              duration: 2000
            })
            return
          }
          // 如果没有prompt_topic_id，或者其他参数不能提交
          if (!_data.prompt_topic_id) {
            this.$notify({
              title: '错误',
              message: '请填写prompt模板ID',
              type: 'error',
              duration: 2000
            })
            return
          }
          // 如果没有topic_folder_id，或者其他参数不能提交
          if (!_data.topic_folder_id) {
            this.$notify({
              title: '错误',
              message: '请填写话题列表目录ID',
              type: 'error',
              duration: 2000
            })
            return
          }
          Post(_data).then(response => {
            this.dialogVisible = false
            this.getList()
            this.notify('添加成功')
          })
          return
        case 'edit':
          // 如果没有name，或者其他参数不能提交
          if (!_data.name) {
            this.$notify({
              title: '错误',
              message: '请填写任务名称',
              type: 'error',
              duration: 2000
            })
            return
          }
          // 如果没有prompt_topic_id，或者其他参数不能提交
          if (!_data.prompt_topic_id) {
            this.$notify({
              title: '错误',
              message: '请填写prompt模板ID',
              type: 'error',
              duration: 2000
            })
            return
          }
          // 如果没有topic_folder_id，或者其他参数不能提交
          if (!_data.topic_folder_id) {
            this.$notify({
              title: '错误',
              message: '请填写话题列表目录ID',
              type: 'error',
              duration: 2000
            })
            return
          }
          Put(_data.id, _data).then(response => {
            this.dialogVisible = false
            this.getList()
            this.notify('更新成功')
          })
          return
        case 'delete':
          Delete(_data.id).then((response) => {
            this.dialogVisible = false
            this.getList()
            this.notify('删除成功')
          })
          return
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(e => {
          this.listLoading = false
        })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    handleGeneratePrompt() {
      if (!this.aiPromptInput || !this.aiPromptInput.trim()) {
        this.$message.error('请先输入需求描述')
        return
      }

      this.aiGenerating = true

      // // 使用模板替换用户内容
      // this.contentFactoryPromptTemplate = '你是一个prompt编辑工具\n' +
      //   '# 你擅长以下能力\n' +
      //   '1. 你拥有30年的SEO经验\n' +
      //   '2. 你非常了解社交营销和内容创建包括tag创建等\n' +
      //   '3. 你熟悉Facebook，twitter, linkedin等社交平台发帖规则和发帖风格\n' +
      //   '3. 你清楚我们账号的主体是一家工厂，做的是全球b2b的业务。\n' +
      //   '# 任务目标\n' +
      //   '根据用户提供的要求，生成专业的prompt框架。\n' +
      //   '框架应该有清晰的结构，使用markdown和<xx></xx>标记语言清晰标记\n' +
      //   '记住用户输入内容会在这个标签那，你需要要求AI分析用户输入内容得到必要信息\n' +
      //   '## 输入分析要求\n' +
      //   '你需要仔细分析<user_content>中的信息，提取以下必要信息：\n' +
      //   '1. 行业和主题关键词\n' +
      //   '2. 产品或服务信息\n' +
      //   '3. 目标受众和其痛点/需求\n' +
      //   '4. 营销目标和号召性用语\n' +
      //   '5. 需要强调的品牌或产品特点\n' +
      //   '6. 特定标签需求\n' +
      //   '7. CTA内容域名，电话，邮箱whatsapp等（如果没有则使用xxxx替代）\n' +
      //   '<user_content>{{user_content}}</user_content>\n' +
      //   '# 输出要求\n' +
      //   '1. 请保留CTA内容的框架接口占位\n' +
      //   '2. 请明确根据用户需求内容和发布场景做字数要求，语气要求，写作风格要求和emjii等要求。\n' +
      //   '3. 请明确用户所在产品或者行业内容帮助完善产品或者行业内容的prompt结构。\n' +
      //   '\n' +
      //   '## Facebook帖子创作指南\n' +
      //   '\n' +
      //   '### 语调与风格\n' +
      //   '- **自然随意**: 使用自然、随意的对话式语调，避免僵硬或过于正式的写作\n' +
      //   '- **信息丰富**: 内容应基于研究、专业知识和真实经验\n' +
      //   '- **实用性强**: 清晰、易懂、功能性和以受众为导向\n' +
      //   '- **原创表达**: 表达方式要有表现力、诚实且新鲜\n' +
      //   '\n' +
      //   '### 帖子结构\n' +
      //   '1. **引人注目的开场 🔍**\n' +
      //   '   - 使用问题或惊叹句吸引注意\n' +
      //   '   - 第一句话必须包含核心关键词\n' +
      //   '   - 添加相关表情符号增强视觉吸引力\n' +
      //   '\n' +
      //   '2. **简明核心内容 ⚙️**\n' +
      //   '   - 保持段落简短（2-3句/段）\n' +
      //   '   - 突出产品/服务的关键优势\n' +
      //   '   - 使用项目符号列出要点（如适用）\n' +
      //   '   - 确保每个句子都为叙述增加价值\n' +
      //   '\n' +
      //   '3. **互动元素 💬**\n' +
      //   '   - 包含问题或投票鼓励评论\n' +
      //   '   - 邀请分享或标记可能感兴趣的人\n' +
      //   '\n' +
      //   '4. **有力的号召性用语(CTA) 🚀**\n' +
      //   '   - 清晰指明下一步行动\n' +
      //   '   - 包含联系方式或链接\n' +
      //   '\n' +
      //   '5. **相关标签 #️⃣**\n' +
      //   '   - 使用5-7个与内容相关的标签\n' +
      //   '   - 包含行业、品牌和产品相关标签\n' +
      //   '### 优化要点\n' +
      //   '- **简洁清晰**: 总字数控制在80-120字，删除多余内容\n' +
      //   '- **表情符号使用**: 适度使用表情符号，避免过度使用\n' +
      //   '- **加粗使用**: 只加粗关键点和重要信息，避免过度加粗\n' +
      //   '- **视觉吸引**: 提示添加高质量图片/视频\n' +
      //   '- **正面积极**: 保持语调积极主动\n' +
      //   '- **时间考量**: 建议最佳发布时间（工作日上午9-11点或下午1-3点）\n' +
      //   '- **合规性**: 确保内容符合Facebook社区规则\n' +
      //   '\n' +
      //   '### 写作禁忌\n' +
      //   '- **陈述显而易见的事实**: 删除废话，直奔主题\n' +
      //   '- **被动语态**: 使用主动语态，让文字富有生命力和行动感\n' +
      //   '- **陈词滥调和行话**: 避免使用"最先进"、"颠覆性"等空洞形容词\n' +
      //   '- **过于复杂的句子**: 简单有效地写作，每个词和句子都应增加价值\n' +
      //   '- **刻板/正式的写作**: 不要使用过于技术性、刻板或正式的写作，使用对话式句子\n' +
      //   '- **以品牌/产品为中心**: 让读者成为内容焦点，确保每一点都服务于他们\n' +
      //   '- **结构不良**: 始终以周密的结构开始，使文章具有紧凑、主题驱动、逻辑流畅的特点'
      // const promptTemplate = this.contentFactoryPromptTemplate.replace('{{user_content}}', this.aiPromptInput);

      // 调用OpenAI API生成prompt
      GetAiContent({
        engine: 'claude-3.7-sonnet', // 使用gpt-4o或其他可用的模型
        aiprompt_id: 277,
        kvs: [{ 'user_content': this.aiPromptInput }],
        prompt_name: 'content_factory_prompt',
        humanway: false // 不使用人工优化
      }).then(response => {
        if (response && response.content) {
          this.generatedPrompt = response.original_content
          this.promptId = ''
          this.$notify({
            title: '成功',
            message: 'Prompt生成成功，您可以进行编辑',
            type: 'success',
            duration: 2000
          })
        } else {
          this.$message.error('生成失败：未获取到有效内容')
        }
      }).catch(error => {
        console.error('生成Prompt错误:', error)
        this.$message.error('生成失败: ' + (error.message || '未知错误'))
      }).finally(() => {
        this.aiGenerating = false
      })
    },
    applyGeneratedPrompt() {
      if (!this.generatedPrompt) return

      // 保存prompt到动态内容组
      this.promptForm.description = this.generatedPrompt
      this.promptForm.keyword = this.aiPromptInput
      this.promptForm.title = this.aiPromptInput
      if (this.promptId) {
        this.promptForm.id = this.promptId
      }
      this.promptChanged = true
      this.savePrompt()
      this.$notify({
        title: '成功',
        message: 'Prompt已保存，请继续完成动态内容设置',
        type: 'success',
        duration: 2000
      })

      // 解析generatedPrompt的内容，自动填充任务名称
      const title = this.generatedPrompt.split('\n')[0].replace('# ', '')
      if (title && !this.temp.name) {
        this.temp.name = title
      }
    },
    addLoopContentGroup() {
      if (!this.temp.loop_content_groups) {
        this.$set(this.temp, 'loop_content_groups', [])
      }
      this.temp.loop_content_groups.push({
        name: '',
        items: [],
        id: null,
        savingName: false,
        savingItems: {}
      })
    },
    removeLoopContentGroup(index) {
      this.temp.loop_content_groups.splice(index, 1)
    },
    addLoopContentItem(groupIndex) {
      if (!this.temp.loop_content_groups[groupIndex].items) {
        this.$set(this.temp.loop_content_groups[groupIndex], 'items', [])
      }
      this.temp.loop_content_groups[groupIndex].items.push('')
    },
    removeLoopContentItem(groupIndex, itemIndex) {
      this.temp.loop_content_groups[groupIndex].items.splice(itemIndex, 1)
    },
    showLoopListContent(row) {
      if (!row.need_loop_content || !row.loop_content_groups || !row.loop_content_groups.length) return

      // 检查是否有关联的ID
      const groupId = row.topic_folder_id || (row.loop_content_groups[0] && row.loop_content_groups[0].id)
      if (groupId) {
        // 找到对应的列表项
        const item = this.contentDataCache[this.loopStrategyName] &&
          this.contentDataCache[this.loopStrategyName].find(item => item.id === groupId)

        if (item) {
          this.previewLoopContent(item)
        } else {
          // 如果没有找到，则显示第一个组的内容
          const firstGroup = {
            id: groupId,
            keyword: row.loop_content_groups.map(g => g.name).join(', '),
            children_count: this.getTotalItems(row.loop_content_groups)
          }
          this.previewLoopContent(firstGroup)
        }
      } else {
        // 如果没有关联ID，则汇总显示全部内容
        const allItems = []
        row.loop_content_groups.forEach(group => {
          if (group.items && group.items.length) {
            group.items.forEach(item => {
              allItems.push({ value: item })
            })
          }
        })

        this.currentLoopList = {
          id: null,
          name: row.loop_content_groups.map(g => g.name).join(', '),
          content: allItems,
          total: allItems.length
        }
        this.loopListDialogVisible = true
      }
    },
    addDynamicContentGroup() {
      this.temp.dynamic_content_groups.push({
        name: '',
        items: [],
        id: null,
        savingName: false,
        savingItems: {}
      })
    },
    removeDynamicContentGroup(index) {
      this.temp.dynamic_content_groups.splice(index, 1)
    },
    addDynamicContentItem(groupIndex) {
      this.temp.dynamic_content_groups[groupIndex].items.push('')
    },
    removeDynamicContentItem(groupIndex, itemIndex) {
      this.temp.dynamic_content_groups[groupIndex].items.splice(itemIndex, 1)
    },
    showDynamicContent(row) {
      if (!row.dynamic_content_groups || !row.dynamic_content_groups.length) return

      this.currentDynamicContent = {
        groups: row.dynamic_content_groups.map(group => ({
          name: group.name,
          items: group.items.map(item => ({ value: item }))
        }))
      }
      this.dynamicContentDialogVisible = true
    },
    saveRandomContent() {
      this.saveContent(this.dynamicStrategyName, 'dynamic_content_groups')
    },
    saveLoopContent() {
      this.saveContent(this.loopStrategyName, 'loop_content_groups')
    },
    saveContent(strategyName, groupsKey) {
      const isLoop = strategyName === this.loopStrategyName
      const savingStateKey = isLoop ? 'savingLoopContent' : 'savingRandomContent'

      // 验证内容数据
      if (!this.temp[groupsKey] || !this.temp[groupsKey].length) {
        this.$notify({
          title: '错误',
          message: isLoop ? '请至少添加一个循环列表组' : '请至少添加一个动态内容组',
          type: 'error',
          duration: 2000
        })
        return
      }

      // 检查每个内容组
      for (let i = 0; i < this.temp[groupsKey].length; i++) {
        const group = this.temp[groupsKey][i]

        // 检查名称
        if (!group.name.trim()) {
          this.$notify({
            title: '错误',
            message: isLoop
              ? `第${i + 1}个循环列表组名称不能为空`
              : `第${i + 1}个动态内容组名称不能为空`,
            type: 'error',
            duration: 2000
          })
          return
        }

        // 检查是否有项目
        if (!group.items || !group.items.length) {
          this.$notify({
            title: '错误',
            message: isLoop
              ? `第${i + 1}个循环列表组"${group.name}"至少需要一项列表项`
              : `第${i + 1}个动态内容组"${group.name}"至少需要一项素材`,
            type: 'error',
            duration: 2000
          })
          return
        }

        // 过滤空的项
        group.items = group.items.filter(item => item.trim() !== '')

        if (!group.items.length) {
          this.$notify({
            title: '错误',
            message: isLoop
              ? `第${i + 1}个循环列表组"${group.name}"的列表项不能为空`
              : `第${i + 1}个动态内容组"${group.name}"的素材内容不能为空`,
            type: 'error',
            duration: 2000
          })
          return
        }
      }

      // 提交数据到后台
      this[savingStateKey] = true

      // 格式化数据
      const data = {
        topicstrategy_name: strategyName,
        content_groups: this.temp[groupsKey]
      }

      PostRandomContent(data)
        .then(response => {
          this.$notify({
            title: '成功',
            message: isLoop ? '循环列表保存成功' : '动态内容保存成功',
            type: 'success',
            duration: 2000
          })
          this[savingStateKey] = false
          // 刷新列表
          this.fetchContentData(strategyName)
        })
        .catch(error => {
          this.$notify({
            title: '错误',
            message: (isLoop ? '循环列表' : '动态内容') + '保存失败: ' + (error.message || '未知错误'),
            type: 'error',
            duration: 2000
          })
          this[savingStateKey] = false
        })
    },
    savePreviewChanges() {
      this.savingPreviewChanges = true

      // 确保有有效的父ID和数据来保存
      if (!this.currentPreviewItemId || !this.materialContentList || !this.materialContentList.length || !this.materialContentList[0] || !this.materialContentList[0].children) {
        this.$message.error('没有可保存的内容或缺少父ID')
        this.savingPreviewChanges = false
        return
      }

      // 过滤掉空的子项并正确标记新旧数据
      const validChildren = this.materialContentList[0].children
        .filter(child => child.description && child.description.trim())
        .map(child => {
          const result = {
            description: child.description
          }

          // 如果是新数据，添加isNew标记
          if (child.isNew) {
            result.isNew = true
          } else if (child.id) {
            result.id = child.id
          } else {
            console.log('')
          }

          return result
        })

      // 构建用于保存子项的数据结构
      const saveData = {
        action: 'update_children',
        topicstrategy_name: this.currentPreviewStrategyName || this.dynamicStrategyName, // 使用当前预览的策略名
        parent_id: this.currentPreviewItemId,
        children: validChildren, // 只发送非空子项
        page: this.dynamicContentPage,
        pagesize: this.dynamicContentPageSize
      }

      console.log('保存动态内容数据:', saveData)

      // 使用PostRandomContent保存
      PostRandomContent(saveData)
        .then(res => {
          console.log('保存动态内容响应:', res)
          if (res.code === 0 || res.data) { // 根据API响应调整条件
            this.$message.success('内容保存成功')

            // 仅刷新当前页面的数据，而不是关闭对话框
            if (this.currentPreviewStrategyName === this.dynamicStrategyName) {
              this.loadDynamicContentItems(this.currentPreviewItemId, this.dynamicContentPage, this.dynamicContentPageSize)
            } else {
              this.loadLoopListItems(this.currentPreviewItemId, this.loopItemPage, this.loopItemPageSize)
            }

            // 更新对应列表的children_count
            this.updateItemCount(this.currentPreviewItemId, this.currentPreviewStrategyName)
          } else {
            this.$message.error(res.message || '内容保存失败')
          }
        })
        .catch(error => {
          console.error('保存动态内容错误:', error)
          this.$message.error('内容保存出错: ' + (error.message || '未知错误'))
        })
        .finally(() => {
          this.savingPreviewChanges = false
        })
    },

    updateItemCount(itemId, strategyName) {
      // 更新缓存中对应项的计数
      if (this.contentDataCache[strategyName]) {
        const index = this.contentDataCache[strategyName].findIndex(item => item.id === itemId)
        if (index !== -1) {
          // 从服务器获取最新的计数
          GetRandomContent(null, qs.stringify({
            strategy_name: strategyName,
            group: itemId,
            count_only: true // 假设API支持只返回计数
          }))
            .then(res => {
              if (res.data && res.data.total) {
                // 更新缓存中的计数
                this.$set(this.contentDataCache[strategyName][index], 'children_count', res.data.total)
              }
            })
            .catch(() => {
              // 出错时不做任何处理
            })
        }
      }
    },
    previewLoopContent(record) {
      if (!record || !record.id) {
        this.$message.error('无效的记录，无法预览')
        return
      }

      this.currentLoopList = {
        id: record.id,
        name: record.keyword || '未命名列表',
        content: [],
        total: record.children_count || 0
      }

      this.loopItemPage = 1
      this.loopListDialogVisible = true
      this.loadLoopListItems(record.id)
    },

    loadLoopListItems(parentId, page = 1, pageSize = 20) {
      this.loadingLoopListItems = true

      // 调用API获取子项数据，添加分页参数
      GetRandomContent(null, qs.stringify({
        strategy_name: this.loopStrategyName,
        group: parentId,
        page: page,
        pagesize: pageSize
      }))
        .then(response => {
          if (response.data) {
            if (Array.isArray(response.data)) {
              // 如果返回是数组，直接设置内容，保留id信息
              this.currentLoopList.content = response.data.map(item => ({
                value: item.description || item.content || '',
                id: item.id || null
              }))
            } else if (response.data.children) {
              // 如果返回对象中有children属性，保留id信息
              this.currentLoopList.content = response.data.children.map(item => ({
                value: item.description || item.content || '',
                id: item.id || null
              }))

              // 如果有分页信息
              if (response.data.total !== undefined) {
                this.currentLoopList.total = response.data.total
              }
            }
          } else {
            this.currentLoopList.content = []
          }
        })
        .catch(error => {
          this.$message.error('获取列表项失败: ' + (error.message || '未知错误'))
          this.currentLoopList.content = []
        })
        .finally(() => {
          this.loadingLoopListItems = false
        })
    },

    handleLoopItemSizeChange(size) {
      this.loopItemPageSize = size
      this.loadLoopListItems(this.currentLoopList.id, this.loopItemPage, size)
    },

    handleLoopItemPageChange(page) {
      this.loopItemPage = page
      this.loadLoopListItems(this.currentLoopList.id, page, this.loopItemPageSize)
    },
    previewDynamicContent(record) {
      if (!record || !record.id) {
        this.$message.error('无效的记录，无法预览')
        return
      }

      // 保存当前ID和策略名，用于后续分页和保存操作
      this.currentPreviewItemId = record.id
      this.currentPreviewStrategyName = this.dynamicStrategyName
      this.dynamicContentTotal = record.children_count || 0
      this.dynamicContentPage = 1

      // 先显示弹窗和加载状态
      this.materialContentList = []
      this.$set(this.loadingStates, 'materialPreview', true)
      this.dynamicContentDialogVisible = true

      // 加载第一页数据
      this.loadDynamicContentItems(record.id, 1, this.dynamicContentPageSize)
    },

    loadDynamicContentItems(parentId, page = 1, pageSize = 20) {
      this.$set(this.loadingStates, 'materialPreview', true)

      // 调用API获取子项数据，添加分页参数
      GetRandomContent(null, qs.stringify({
        strategy_name: this.dynamicStrategyName,
        group: parentId,
        page: page,
        pagesize: pageSize
      }))
        .then(response => {
          if (response.data) {
            if (Array.isArray(response.data)) {
              // 如果是数组，构建父对象和children，保留id信息
              this.materialContentList = [{
                id: parentId,
                keyword: (this.contentDataCache[this.dynamicStrategyName] &&
                  this.contentDataCache[this.dynamicStrategyName].find(i => i.id === parentId) &&
                  this.contentDataCache[this.dynamicStrategyName].find(i => i.id === parentId).keyword) || '动态内容',
                children: response.data.map(item => ({
                  description: item.description || item.content || '',
                  id: item.id || null
                }))
              }]
            } else if (response.data.children) {
              // 如果返回对象中有children属性，保留id信息
              this.materialContentList = [{
                id: parentId,
                keyword: response.data.keyword || '动态内容',
                children: response.data.children.map(item => ({
                  description: item.description || item.content || '',
                  id: item.id || null
                }))
              }]

              // 如果有分页信息
              if (response.data.total !== undefined) {
                this.dynamicContentTotal = response.data.total
              }
            }
          } else {
            this.materialContentList = [{
              id: parentId,
              keyword: (this.contentDataCache[this.dynamicStrategyName] &&
                this.contentDataCache[this.dynamicStrategyName].find(i => i.id === parentId) &&
                this.contentDataCache[this.dynamicStrategyName].find(i => i.id === parentId).keyword) || '动态内容',
              children: []
            }]
          }
        })
        .catch(error => {
          this.$message.error('获取动态内容失败: ' + (error.message || '未知错误'))
          this.materialContentList = [{
            id: parentId,
            keyword: (this.contentDataCache[this.dynamicStrategyName] &&
              this.contentDataCache[this.dynamicStrategyName].find(i => i.id === parentId) &&
              this.contentDataCache[this.dynamicStrategyName].find(i => i.id === parentId).keyword) || '动态内容',
            children: []
          }]
        })
        .finally(() => {
          this.$set(this.loadingStates, 'materialPreview', false)
        })
    },

    handleDynamicContentSizeChange(size) {
      this.dynamicContentPageSize = size
      this.loadDynamicContentItems(this.currentPreviewItemId, this.dynamicContentPage, size)
    },

    handleDynamicContentPageChange(page) {
      this.dynamicContentPage = page
      this.loadDynamicContentItems(this.currentPreviewItemId, page, this.dynamicContentPageSize)
    },
    copyLoopShortcode(id) {
      this.copyContentShortcode(id, 'loop', 'item_index')
    },
    copyShortcode(id) {
      this.copyContentShortcode(id, 'topic', 'description_random_1')
    },
    copyContentShortcode(id, prefix, suffix) {
      if (!id) {
        this.$message.error('ID不能为空')
        return
      }

      // 创建shortcode格式
      const shortcode = `{{${prefix}_${id}_${suffix}}}`

      // 复制到剪贴板
      if (navigator.clipboard) {
        // 现代浏览器API
        navigator.clipboard.writeText(shortcode)
          .then(() => {
            this.$message.success(`Shortcode已复制: ${shortcode}`)
          })
          .catch(err => {
            // 创建临时文本区域来复制
            console.error('复制失败:', err)
            this.fallbackCopyTextToClipboard(shortcode)
          })
      } else {
        // 不支持clipboard API的浏览器
        this.fallbackCopyTextToClipboard(shortcode)
      }
    },
    fallbackCopyTextToClipboard(text) {
      const textArea = document.createElement('textarea')
      textArea.value = text

      // 避免滚动到底部
      textArea.style.top = '0'
      textArea.style.left = '0'
      textArea.style.position = 'fixed'

      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()

      try {
        const successful = document.execCommand('copy')
        if (successful) {
          this.$message.success(`Shortcode已复制: ${text}`)
        } else {
          this.$message.error('复制失败')
        }
      } catch (err) {
        this.$message.error('复制失败: ' + err)
      }

      document.body.removeChild(textArea)
    },
    addItemToPreview(group) {
      if (!group) return
      if (!group.children) {
        this.$set(group, 'children', [])
      }
      group.children.push({
        'description': '',
        'isNew': true,
        'id': null
      })
    },
    removeItemFromPreview(group, index) {
      group.children.splice(index, 1)
    },
    fetchContentData(strategyName, parentId = null) {
      const isLoadingKey = parentId ? 'materialPreview' : strategyName
      this.$set(this.loadingStates, isLoadingKey, true)
      console.log(`开始获取内容: strategy=${strategyName}, parentId=${parentId}`)

      return GetRandomContent(null, qs.stringify({
        strategy_name: strategyName,
        group: parentId,
        // 如果是父级列表，只获取基本信息；如果是子项列表，则进行分页
        page: parentId ? 1 : 1,
        pagesize: parentId ? 20 : 1000 // 顶级列表可以获取更多，因为通常数量不会很大
      }))
        .then(response => {
          console.log(`获取内容成功: strategy=${strategyName}, parentId=${parentId}`, response)

          if (response.data) {
            if (parentId) {
              // 查看子项时不再存入缓存，直接返回给调用方使用
              this.materialContentList = Array.isArray(response.data) ? response.data : [response.data]
              // 不再设置缓存中的children属性
            } else {
              if (Array.isArray(response.data)) {
                // 只缓存顶级数据，不包含children
                const topLevelData = response.data.filter(item => !item.parent_id).map(item => {
                  // 确保保留children_count字段，但不保存children数据
                  const { ...rest } = item
                  return rest
                })
                this.$set(this.contentDataCache, strategyName, topLevelData)
                console.log(`设置缓存: strategy=${strategyName}`, topLevelData)
              } else {
                console.warn(`获取顶级列表时数据格式非数组: strategy=${strategyName}`, response.data)
                this.$set(this.contentDataCache, strategyName, [])
              }
            }
          } else {
            console.warn(`获取内容响应无效: strategy=${strategyName}, parentId=${parentId}`, response)
            if (!parentId) {
              this.$set(this.contentDataCache, strategyName, [])
            }
          }
          return response
        })
        .catch(error => {
          console.error(`获取内容失败: strategy=${strategyName}, parentId=${parentId}`, error)
          this.$notify({
            title: '错误',
            message: `获取内容列表失败 (${strategyName}): ` + (error.message || '未知错误'),
            type: 'error',
            duration: 2000
          })
          if (!parentId) {
            this.$set(this.contentDataCache, strategyName, [])
          }
          return Promise.reject(error)
        })
        .finally(() => {
          this.$set(this.loadingStates, isLoadingKey, false)
          console.log(`结束获取内容: strategy=${strategyName}, parentId=${parentId}`)
        })
    },
    getTotalItems(groups) {
      let totalItems = 0
      if (Array.isArray(groups)) {
        groups.forEach(group => {
          totalItems += group.items.length
        })
      }
      return totalItems
    },
    saveContentGroupName(groupIndex, strategyName) {
      const groupKey = strategyName === this.dynamicStrategyName ? 'dynamic_content_groups' : 'loop_content_groups'
      const group = this.temp[groupKey][groupIndex]

      if (!group.name.trim()) {
        this.$notify({
          title: '错误',
          message: strategyName === this.dynamicStrategyName ? '动态内容名称不能为空' : '循环列表名称不能为空',
          type: 'error',
          duration: 2000
        })
        return
      }

      group.savingName = true

      // 准备提交的数据
      const data = {
        action: 'save_group',
        topicstrategy_name: strategyName,
        group: {
          name: group.name,
          id: group.id // 如果是更新，会有ID
        }
      }

      PostRandomContent(data)
        .then(response => {
          // 假设后台返回的数据包含保存后的ID
          if (response.data && response.data.id) {
            group.id = response.data.id
            this.$notify({
              title: '成功',
              message: strategyName === this.dynamicStrategyName ? '动态内容组名称保存成功' : '循环列表组名称保存成功',
              type: 'success',
              duration: 2000
            })
            // 刷新列表获取最新数据
            this.fetchContentData(strategyName)
          } else {
            this.$notify({
              title: '错误',
              message: '保存失败: 未获取到ID',
              type: 'error',
              duration: 2000
            })
          }
        })
        .catch(error => {
          this.$notify({
            title: '错误',
            message: '保存失败: ' + (error.message || '未知错误'),
            type: 'error',
            duration: 2000
          })
        })
        .finally(() => {
          group.savingName = false
        })
    },
    saveContentItem(groupIndex, itemIndex, strategyName) {
      const groupKey = strategyName === this.dynamicStrategyName ? 'dynamic_content_groups' : 'loop_content_groups'
      const group = this.temp[groupKey][groupIndex]
      const itemContent = group.items[itemIndex]

      if (!group.id) {
        this.$notify({
          title: '错误',
          message: strategyName === this.dynamicStrategyName ? '请先保存动态内容组名称' : '请先保存循环列表组名称',
          type: 'error',
          duration: 2000
        })
        return
      }

      if (!itemContent.trim()) {
        this.$notify({
          title: '错误',
          message: strategyName === this.dynamicStrategyName ? '动态内容素材不能为空' : '循环列表项不能为空',
          type: 'error',
          duration: 2000
        })
        return
      }

      // 初始化保存状态对象
      if (!group.savingItems) {
        this.$set(group, 'savingItems', {})
      }
      this.$set(group.savingItems, itemIndex, true)

      // 准备提交的数据
      const data = {
        action: 'save_item',
        topicstrategy_name: strategyName,
        item: {
          group_id: group.id,
          content: itemContent,
          index: itemIndex
        }
      }

      PostRandomContent(data)
        .then(response => {
          this.$notify({
            title: '成功',
            message: strategyName === this.dynamicStrategyName ? '动态内容素材保存成功' : '循环列表项保存成功',
            type: 'success',
            duration: 2000
          })
          this.$set(group.savingItems, itemIndex, false)
        })
        .catch(error => {
          this.$notify({
            title: '错误',
            message: '保存失败: ' + (error.message || '未知错误'),
            type: 'error',
            duration: 2000
          })
          this.$set(group.savingItems, itemIndex, false)
        })
    },
    addLoopListItem() {
      if (!this.currentLoopList) return

      this.currentLoopList.content.push({
        value: '',
        isNew: true,
        id: null
      })
    },

    removeLoopListItem(index) {
      if (!this.currentLoopList || !this.currentLoopList.content) return

      this.currentLoopList.content.splice(index, 1)
    },

    saveLoopListChanges() {
      // Check if we have valid list and ID
      if (!this.currentLoopList || !this.currentLoopList.id) {
        this.$message.error('无法保存：缺少列表ID')
        return
      }

      // Set loading state
      this.savingLoopListChanges = true

      // Process items
      const validItems = this.currentLoopList.content
        .filter(item => item.value && item.value.trim())
        .map(item => {
          const result = {
            description: item.value
          }

          if (item.isNew) {
            result.isNew = true
          } else if (item.id) {
            result.id = item.id
          }

          return result
        })

      // Create data object
      const saveData = {
        action: 'update_children',
        topicstrategy_name: this.loopStrategyName,
        parent_id: this.currentLoopList.id,
        children: validItems,
        page: this.loopItemPage,
        pagesize: this.loopItemPageSize
      }

      // Send request
      console.log('保存循环列表数据:', saveData)

      PostRandomContent(saveData)
        .then(res => {
          console.log('保存循环列表响应:', res)
          if (res.code === 0 || res.data) {
            this.$message.success('列表项保存成功')
            this.loadLoopListItems(this.currentLoopList.id, this.loopItemPage, this.loopItemPageSize)
            this.updateItemCount(this.currentLoopList.id, this.loopStrategyName)
          } else {
            this.$message.error(res.message || '保存失败')
          }
        })
        .catch(error => {
          console.error('保存循环列表错误:', error)
          this.$message.error('保存出错: ' + (error.message || '未知错误'))
        })
        .finally(() => {
          this.savingLoopListChanges = false
        })
    },
    saveLoopListItem(index) {
      // 检查是否有有效的列表和ID
      if (!this.currentLoopList || !this.currentLoopList.id) {
        this.$message.error('无法保存：缺少列表ID')
        return
      }

      const item = this.currentLoopList.content[index]
      if (!item || !item.value || !item.value.trim()) {
        this.$message.error('内容不能为空')
        return
      }

      // 设置当前项的加载状态
      this.$set(item, 'saving', true)

      // 创建请求数据
      const saveData = {
        action: 'save_single_item',
        topicstrategy_name: this.loopStrategyName,
        parent_id: this.currentLoopList.id,
        item: {
          description: item.value,
          id: item.id || null,
          isNew: item.isNew || false,
          index: index
        }
      }

      // 发送请求
      PostRandomContent(saveData)
        .then(res => {
          if (res.code === 0 || res.data) {
            this.$message.success('列表项保存成功')
            // 如果是新添加的项目，更新ID
            if (res.data && res.data.id) {
              this.$set(item, 'id', res.data.id)
              this.$set(item, 'isNew', false)
            }
          } else {
            this.$message.error(res.message || '保存失败')
          }
        })
        .catch(error => {
          console.error('保存列表项错误:', error)
          this.$message.error('保存出错: ' + (error.message || '未知错误'))
        })
        .finally(() => {
          this.$set(item, 'saving', false)
        })
    },
    saveDynamicContentItem(group, index) {
      // 确保有有效的父ID和数据来保存
      if (!this.currentPreviewItemId || !group || !group.children) {
        this.$message.error('没有可保存的内容或缺少父ID')
        return
      }

      const item = group.children[index]
      if (!item || !item.description || !item.description.trim()) {
        this.$message.error('内容不能为空')
        return
      }

      // 设置当前项的加载状态
      this.$set(item, 'saving', true)

      // 构建用于保存单个子项的数据结构
      const saveData = {
        action: 'save_single_item',
        topicstrategy_name: this.currentPreviewStrategyName || this.dynamicStrategyName,
        parent_id: this.currentPreviewItemId,
        item: {
          description: item.description,
          id: item.id || null,
          isNew: item.isNew || false,
          index: index
        }
      }

      // 使用PostRandomContent保存
      PostRandomContent(saveData)
        .then(res => {
          if (res.code === 0 || res.data) {
            this.$message.success('内容保存成功')
            // 如果是新添加的项目，更新ID
            if (res.data && res.data.id) {
              this.$set(item, 'id', res.data.id)
              this.$set(item, 'isNew', false)
            }
          } else {
            this.$message.error(res.message || '内容保存失败')
          }
        })
        .catch(error => {
          console.error('保存动态内容错误:', error)
          this.$message.error('内容保存出错: ' + (error.message || '未知错误'))
        })
        .finally(() => {
          this.$set(item, 'saving', false)
        })
    },
    savePrompt() {
      this.savingPrompt = true

      const params = {
        topicstrategy_name: '内容工厂-prompt',
        action: 'save_prompt_topic',
        title: this.promptForm.title,
        description: this.promptForm.description,
        keyword: this.promptForm.keyword
      }
      // 如果是编辑模式，添加ID参数
      if (this.promptId) {
        params.id = this.promptId
      }

      PostRandomContent(params)
        .then(response => {
          if (response.data && response.data.id) {
            this.promptId = response.data.id

            this.temp.prompt_topic_id = response.data.id
            this.promptChanged = false
            this.$notify({
              title: '成功',
              message: this.promptId ? 'Prompt更新成功' : 'Prompt保存成功',
              type: 'success',
              duration: 2000
            })
          }
        })
        .catch(error => {
          this.$notify({
            title: '错误',
            message: '保存失败：' + (error.message || '未知错误'),
            type: 'error',
            duration: 2000
          })
        })
        .finally(() => {
          this.savingPrompt = false
        })
    },
    editPrompt() {
      this.isEditing = true
      // 这里可以添加获取最新数据的逻辑，如果需要的话
      this.$notify({
        title: '提示',
        message: '您正在编辑已保存的Prompt',
        type: 'info',
        duration: 2000
      })
    },
    handlePromptDialogClose() {
      if (this.promptChanged) {
        this.$confirm('您有未保存的Prompt修改，是否放弃修改？', '提示', {
          confirmButtonText: '放弃',
          cancelButtonText: '继续编辑',
          type: 'warning'
        }).then(() => {
          this.promptDialogVisible = false
          this.promptChanged = false
        }).catch(() => {
          // 用户选择继续编辑，不关闭对话框
        })
      } else {
        this.promptDialogVisible = false
      }
    },
    openPromptDialog(data = null) {
      if (data && data.id) {
        this.promptId = data.id
        this.promptForm.description = data.description || ''
        this.promptForm.keyword = data.keyword || ''
        this.isEditing = true
      } else {
        this.promptId = null
        this.promptForm.description = ''
        this.promptForm.keyword = ''
        this.isEditing = false
      }
      this.promptChanged = false
      this.promptDialogVisible = true
    }
  }
}
</script>

<style scoped>

.el-header, .el-footer {
  background-color: #fff;
  color: #333;
  text-align: left;
  line-height: 60px;
}

.el-aside {
  background-color: #fff;
  border-left: 1px solid #ebeef5;
  color: #333;
  padding-top: 20px;
  padding-left: 10px;
  line-height: 250px;
}

.el-main {
  background-color: #fff;
  color: #333;
  text-align: center;
}

body > .el-container {
  margin-bottom: 40px;
}

.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
  line-height: 260px;
}

.el-container:nth-child(7) .el-aside {
  line-height: 320px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

/*.top {*/
/*padding-left: 20px;*/
/*padding-right: 20px;*/
/*margin-bottom: 5px;*/
/*margin-top: 28px;*/
/*}*/

/*.head {*/
/*width: calc(20% - 70px);*/
/*}*/

/*.web {*/
/*margin-top: 10px;*/
/*margin-bottom: 10px;*/
/*display: inline-block;*/
/*width: 100%;*/
/*}*/

.web >>> .el-input {
  min-width: 1200px;
}

.app-container >>> .el-dialog {
  margin-top: 48px !important;
  margin-bottom: 68px;
}

.mt-detail:hover, .svg-icon:hover {
  cursor: pointer;
}

.mt-detail {
  color: #1976d2;
}

.mt-dialog >>> .el-dialog {
  margin: 88px auto !important;
}

.clearfix ::after {
  content: "";
  clear: both
}

.mt-table {
  color: black;
  padding: 20px;
}

.mt-pagination {
  float: right;
  margin-top: 10px;
}

.mt-top {
  margin: 15px 0;
}

.mt-row-btn {
  float: right;
  vertical-align: middle;
  color: white;
}

.mt-btn {
  background-color: rgba(0, 0, 0, 0);
  background-image: none;
  border-radius: 1000px;
  border-bottom-style: solid;
  border-bottom-width: 1px;
  border-collapse: collapse;
  border-image-outset: 0px;
  border-image-repeat: stretch;
  border-image-slice: 100%;
  border-image-source: none;
  border-image-width: 1;
  border-left-style: solid;
  border-left-width: 1px;
  border-right-style: solid;
  border-right-width: 1px;
  border-top-style: solid;
  border-top-width: 1px;
  box-sizing: border-box;
  color: #46be8a;
  cursor: pointer;
  display: block;
  float: right;
  font-family: "Helvetica Neue", Helvetica, Tahoma, Arial, "Microsoft Yahei", "Hiragino Sans GB", "WenQuanYi Micro Hei", sans-serif;
  font-size: 14px;
  font-weight: 400;
  height: 26px;
  hyphens: manual;
  line-height: 14px;
  margin-bottom: 0px;
  margin-right: 10px;
  padding: 5px;
  text-align: center;
  text-decoration-color: rgb(82, 96, 105);
  text-decoration-line: none;
  text-decoration-style: solid;
  text-rendering: optimizeLegibility;
  text-size-adjust: 100%;
  touch-action: manipulation;
  transition-delay: 0s, 0s, 0s, 0s;
  transition-duration: 0.2s, 0.2s, 0.2s, 0.2s;
  transition-property: border, color, width, background-color;
  transition-timing-function: linear, linear, linear, linear;
  user-select: none;
  vertical-align: middle;
  visibility: visible;
  white-space: nowrap;
  background: white;
}

.mt-btn:hover {
  background: #46be8a;
}

.mt-btn:hover + .mt-icon {
  color: #fff;
}

.danger:hover {
  background-color: #F56C6C;
}

.danger {
  color: #F56C6C;
}

.default:hover {
  background-color: #62a8ea;
}

.default {
  color: #62a8ea;
}

.edit:hover {
  background-color: #909399;
}

.edit {
  color: #909399;
}

.mt-row-title {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: calc(100% - 220px);
  display: inline-block;
  vertical-align: middle;
}

.mt-row-btns {
  float: right;
  margin-right: 10px;
  z-index: 10000;
}

</style>
